<?php

namespace App\Http\Controllers;

use App\Model\BmrUserModel;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Request;

class Controller extends BaseController
{
    //是否需要登录
    protected $login = true;
    //登录用户
    protected $bmrUser = null;
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        //检查登录
        $this->checkLogin();
    }

    //检查登录
    protected function checkLogin() {
        if ($this->login)
        {
            if (!($user = $this->getLoginUser())) {
                redirect('/login')->send();
            }
            $this->setLoginUser($user);
        }
    }

    /**
     * 已经登录
     * @return BmrUserModel $user
     */
    protected function getLoginUser() {
        return  Request::session()->get('user', null);
    }

    /**设置登录用户
     * @param BmrUserModel $user
     */
    protected function setLoginUser(BmrUserModel $user) {
        $this->bmrUser = $user;
        Request::session()->put('user', $user);
    }

    /**
     * 用户登出
     */
    protected function destroyUser() {
        $this->bmrUser = null;
        Request::session()->put('user', null);
    }

    /**api成功返回
     * @param $data
     * @return array
     */
    protected function apiSuccess($data) {
        return [
            'error' => 0,
            'data'  => $data
        ];
    }

    /**api失败返回
     * @param $msg
     * @param int $code
     * @return array
     */
    protected function apiError($msg, $code = -1) {
        return [
            'error' => $code,
            'msg'  => $msg
        ];
    }
}
